package com.wanlian.router.net;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.smart.android.utils.FileUtils;
import com.wanlian.router.bean.UpTask;
import com.wanlian.router.bean.UpTaskDatas;
import com.wanlian.router.net.file.listener.ProgressListener;
import com.wanlian.router.net.file.utils.OKHttpUtils;
import com.wanlian.router.net.internal.INetCallBack;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Hyu on 2018/10/20.
 * Email: fvaryu@163.com
 */
public class UploadServer extends IntentService {
    private final static String CACHE_NAME  = "upload.json";

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */

    private static Queue<UpTask> mUpTasks;
    private final ExecutorService mExecutor = Executors.newFixedThreadPool(5);

    public static UpTaskDatas readFile() {
        String path = String.format("%s/%s", FileUtils.getCachePath(), "yun");


        File file = new File(path, CACHE_NAME);
        if (!file.exists()) {
            FileUtils.createFile(path, CACHE_NAME);
        }

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String line = br.readLine();
            if (TextUtils.isEmpty(line)) {
                return null;
            }

            return new Gson().fromJson(line, UpTaskDatas.class);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static void addTask(UpTask task) {
        if (mUpTasks == null) {
            mUpTasks = new ConcurrentLinkedDeque<UpTask>();
        }
        mUpTasks.add(task);
    }


    public UploadServer() {
        this("u_task");
    }

    public UploadServer(String name) {
        super(name);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mUpTasks = new ConcurrentLinkedDeque<UpTask>();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {


        while (true) {

            if (!mUpTasks.isEmpty()) {
                final UpTask task = mUpTasks.poll();

                mExecutor.submit(new Task( task, this));
            }


            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
        }



    }

    class Task implements  Runnable {
    private  UpTask mUpTask;
    private Context mContext;

        public Task(UpTask upTask, Context context) {
            mUpTask = upTask;
            mContext = context;
        }


        @Override
        public void run() {

            List<String> f = new ArrayList<>();
            f.add(mUpTask.getFilePath());
            OKHttpUtils.doPostRequest("http://47.75.195.106/router/upload/file/upload", f, new ProgressListener() {
                @Override
                public void onProgress(long currentBytes, long contentLength, boolean done) {
                    System.out.println("current=" + currentBytes + ",contentLength=" + contentLength);
                }
            }, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        ResponseData responseData = new Gson().fromJson(response.body().string(), ResponseData.class);
                        if (responseData.isSuccess()) {
                            NetWorkingClient.getInstance().putFileToYunSys(UploadServer.this,
                                mUpTask.getFileName(), mUpTask.getLength() / 1024.f, mUpTask.getFileType(), responseData.getUrl(), new INetCallBack() {
                                    @Override
                                    public void onFinish(ResponseData response, @Nullable Object o) {

                                    }
                                });
                        }
                    }
                }
            });
//            OKHttpUtils.getOkHttpClientInstance().
//            NetWorkingClient.getInstance().uploadFile(mContext, new File(mUpTask.getFilePath()), new INetCallBack() {
//                @Override
//                public void onFinish(ResponseData response, @Nullable Object o) {
//                    if (response.isSuccess()) {
//
//                        NetWorkingClient.getInstance().putFileToYunSys(UploadServer.this,
//                                mUpTask.getFileName(), mUpTask.getLength() / 1024.f, mUpTask.getFileType(), response.getUrl(), new INetCallBack() {
//                                    @Override
//                                    public void onFinish(ResponseData response, @Nullable Object o) {
//
//                                    }
//                                });
//                    }
//                }
//            });
        }
    }
}
